package com.ihrm.modules.sys.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ihrm.common.utils.Constant;
import com.ihrm.modules.sys.dao.PermissionDao;
import com.ihrm.modules.sys.dao.UserDao;
import com.ihrm.modules.sys.entity.PermissionEntity;
import com.ihrm.modules.sys.entity.UserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 认证
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserDao sysUserDao;
    @Autowired
    private PermissionDao permissionDao;
    
    /**
     * 授权(验证权限时调用)
     */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserEntity user = (UserEntity)principals.getPrimaryPrincipal();
		String userId = user.getId();
		
		List<String> permsList;
		
		//系统管理员，拥有最高权限
		if(StringUtils.equals(userId,Constant.SUPER_ADMIN)){
			List<PermissionEntity> menuList = permissionDao.selectList(null);
			permsList = new ArrayList<>(menuList.size());
			for(PermissionEntity menu : menuList){
				permsList.add(menu.getPerms());
			}
		}else{
			permsList = permissionDao.queryBtnsByUserId(userId);
		}

		//用户权限列表
		Set<String> permsSet = new HashSet<>();
		for(String perms : permsList){
			if(StringUtils.isBlank(perms)){
				continue;
			}
			permsSet.addAll(Arrays.asList(perms.trim().split(",")));
		}
		
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken)authcToken;

		//查询用户信息
		UserEntity user = sysUserDao.selectOne(new QueryWrapper<UserEntity>().eq("mobile", token.getUsername()));
		//账号不存在
		if(user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		//账号锁定
		if(user.getEnableState() == 0){
			throw new LockedAccountException("账号已引用,请联系管理员");
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getMobile()), getName());
		return info;
	}

	@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
		shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
		shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
		super.setCredentialsMatcher(shaCredentialsMatcher);
	}

	/**
	 * 清除当前用户的权限认证缓存
	 *
	 * @param principals 权限信息 身份集合
	 */
	@Override
	public void clearCache(PrincipalCollection principals) {
		super.clearCache(principals);
	}
}
